package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Follow;
import com.hmdp.mapper.FollowMapper;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private IUserService userService;

    /**
     * 查询是否关注
     * @param id
     * @return
     */
    @Override
    public Result isFollow(Long id) {
        //获取用户id
        UserDTO user = UserHolder.getUser();
        if(user==null){
            return Result.fail("未登录");
        }
        //查询是否关注
        // 先查redis
        Set<String> members = stringRedisTemplate.opsForSet().members("follow:" + user.getId());
        if(members == null || members.isEmpty() ){
            // 没有关注对象
            return Result.ok(false);
        }
        // 再查数据库
        Long count = query().eq("user_id", user.getId()).eq("follow_user_id", id).count();
        // 3.判断
        return Result.ok(count > 0);
    }

    /**
     * 关注与取消关注
     * @param id 被关注用户id
     * @param flag 判断是否关注与取消
     * @return
     */
    @Override
    public Result doFollow(Long id, Boolean flag) {
        //获取用户id
        UserDTO user = UserHolder.getUser();
        if(user==null){
            return Result.fail("未登录");
        }
        Long userId = user.getId();
        String key = "follow:" + userId;
        if(flag){
            // 2.关注，新增数据
            Follow follow = new Follow();
            follow.setUserId(userId);
            follow.setFollowUserId(id);
            boolean isSuccess = save(follow);
            if(isSuccess){
                // 添加到redis 以便共同关注 求交集
                stringRedisTemplate.opsForSet().add(key, String.valueOf(id));
            }
        }else {
            // 3.取关，删除 delete from tb_follow where user_id = ? and follow_user_id = ?
            boolean isSuccess = remove(new QueryWrapper<Follow>()
                    .eq("user_id", userId).eq("follow_user_id", id));
            if(isSuccess){
                // 移除
                stringRedisTemplate.opsForSet().remove(key, String.valueOf(id));
            }
        }
        return Result.ok();
    }

    @Override
    public Result getFollowCommon(String id) {
        // 获取用户ID
        Long userId = UserHolder.getUser().getId();
        String key1 = "follow:" + userId;
        String key2 = "follow:" + id;
        // 获取共同关注 用户id
        Set<String> intersect = stringRedisTemplate.opsForSet().intersect(key1, key2);
        if (intersect == null || intersect.isEmpty()) {
            // 无交集
            return Result.ok(Collections.emptyList());
        }
        // 解析数据
        List<Long> ids = intersect.stream().map(Long::valueOf).collect(Collectors.toList());

        // 4.查询用户
        List<UserDTO> users = userService.listByIds(ids)
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        return Result.ok(users);

    }
}
